package allrobots.RobotThread;

import allrobots.DispensingMachine.DispensingMachinePosition;
import allrobots.DispensingMachine.WaitPosition;
import allrobots.Robot.RobotMessage;
import allrobots.Robot.RobotMessageMap;
import allrobots.Robot.RobotsOosAndOis;
import allrobots.Robot.RobotsSocketMap;
import allrobots.TraceAndAvoid.Move;
import allrobots.pojo.BroadcastMessage;
import t10086.Data.Map.GridType;
import t10086.Data.Robot.RobotInfo;
import t10086.Data.Robot.RobotStatus;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

public class RegularReplies implements Runnable {
    private Integer robotId;
    private ObjectOutputStream oos;//与主系统的oos
    private Socket reactSocket;//与发药机连接或者药剂师连接的socket

    public RegularReplies(Integer robotId, Socket reactSocket) {
        this.robotId = robotId;
        this.oos = RobotsSocketMap.robotsSocketMap.get(robotId).getOos();
        this.reactSocket = reactSocket;
    }

    @Override
    public void run() {
        int flag = 0;
        while (flag == 0) {
            try {
                RobotMessage robotMessage = RobotMessageMap.robotMap.get(robotId);
                if (robotMessage.getRobotStatus().equals(RobotStatus.MOVING) ||
                        robotMessage.getRobotStatus().equals(RobotStatus.QUEUING)) {
                    // 进行一次移动避障
                    if (BroadcastMessage.broadcastMessage.getMap().getGrid(RobotMessageMap.robotMap.get(robotId).getPosition()).getGridType() == GridType.COLLISION) {
                        System.out.println("我撞上了");
                        return;
                    }
//                    System.out.println("机器人终点"+robotMessage.getTermination());
//                    System.out.println("窗口位置"+BroadcastMessage.broadcastMessage.get(robotId).getWindowMap().get(robotMessage.getWindow()));
//                    System.out.println(WaitPosition.waitposition.get(robotId));
                    if (robotMessage.getTermination().equals(WaitPosition.waitposition.get(robotId))) {
                        // 往排队队列移动
                        flag = new Move(reactSocket, robotId).avoid();
                    } else if (robotMessage.getTermination().equals(DispensingMachinePosition.windowPosition)) {
                        // 往发药机窗口移动
                        flag = new Move(reactSocket, robotId).avoid();
                    } else if (robotMessage.getTermination().equals(BroadcastMessage.broadcastMessage.getWindowMap().get(robotMessage.getWindow()))) {
                        // 发药机移动
                        new Move(reactSocket, robotId).queueLogic();
                    } else {
                        // 移动回家
                        flag = new Move(reactSocket, robotId).avoid();
                    }

                    // 向系统定期发送信息
                    RobotMessage robot = RobotMessageMap.robotMap.get(robotId);
                    RobotInfo submit_robotInfo = new RobotInfo(robot.getSerialNum(), robot.getPosition(), robot.getNext(), robot.getTermination(), robot.getRobotStatus(), robot.getListenedSocket());
                    submit_robotInfo.setWindow(robot.getWindow());
                    submit_robotInfo.setSelfMovingNumber(robot.getSelfMovingNumber());
                    submit_robotInfo.setSelfQueuingNumber(robot.getSelfQueuingNumber());
                    // 汇报自己的信息（已完成）
                    Message toSystemMessage = new Message(MessageType.ROBOT_UPLOAD, submit_robotInfo);
                    // 发送者
                    toSystemMessage.setSender((InetSocketAddress) RobotsSocketMap.robotsSocketMap.get(robotId).getSocket().getLocalSocketAddress());
                    // 接收者
                    toSystemMessage.setReceiver((InetSocketAddress) RobotsSocketMap.robotsSocketMap.get(robotId).getSocket().getRemoteSocketAddress());
                    try {
                        // 深拷贝 toSystemMessage
                        Message clonedMessage = (Message) deepClone(toSystemMessage);
                        // 发送拷贝后的消息
                        oos.writeObject(clonedMessage);
                        oos.flush();
                        Thread.sleep(50);
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                        // 发生异常时，关闭 socket 并停止线程
                        return; // 退出线程
                    }
                }
            } catch (Exception e) {
                // 处理其他可能的异常
                e.printStackTrace();
                return; // 退出线程
            }
        }
    }

    public static Object deepClone(Object object) throws IOException, ClassNotFoundException {
        // 写入字节流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);

        // 从字节流中读取
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

        return objectInputStream.readObject();
    }

}
